// pages/index/good-spell/good-spell.js
let app = getApp();
const moment = require('../../../utils/moment.min.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: '',
    orderId: '',
    promoter: '',//发起人 团主id
    productId: '',//商品id
    orderStatus: '',//订单状态，-1订单已取消
    goods: {},
    invitationShow: false,
    timeData: {},//倒计时对象
    serverTime: null,//当前时间戳
    tShopId: '',//分享链接的门店id
  },

  getGoodInfo () {
    let _this = this
    if (_this.data.user.id == null) return
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/shop/products/detail',
      data: {
        productId: _this.data.productId,
        memberId: _this.data.user.id,
        orderId: _this.data.orderId,
      },
      load: 1
    }).then((res) => {
      let data = res.data.data;
      console.log("数据返回："+data.upEndTime)
      console.log("时间戳："+moment(data.upEndTime).valueOf())
      console.log("差："+ (moment(data.upEndTime).valueOf() - _this.data.serverTime))
      data.upEndTime = (moment(data.upEndTime).valueOf() - _this.data.serverTime) > 0 ? moment(data.upEndTime).valueOf() - _this.data.serverTime : 0;
      console.log("结果："+data.upEndTime)
      //数组逆排序
      if(data.spellGroupOrdS[0].avatars) data.spellGroupOrdS[0].avatars.reverse();

      _this.setData({
        goods: data,
        invitationShow: data.isJoin == 1 ? false : _this.data.orderStatus != -1 ? true : false
      })
    })
  },
  //注册绑定门店
  saveShopId(){
    let _this = this;
    app.requestUrl({
      method: 'POST',
      url: '/wxapi/shop/bind',
      data: {
        memberId: _this.data.user.id,
        teamId: app.getShop().id
      }
    }).then((res) => {
      _this.setUserInfo();
    })
  },
  setUserInfo () {
    let _this = this
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/member',
      data: {
        id: _this.data.user.id,
        getShop: true
      }
    }).then((res) => {
      // if (res.data.shop != '') wx.setStorageSync('shopInfo', JSON.stringify(res.data.shop))
      if (res.data.data != '') wx.setStorageSync('userInfo', JSON.stringify(res.data.data))
      _this.setData({
        user: app.getUser()
      })
    })
  },

  //参与拼团
  toPlaceOrderEntity(){
    let isSpellgroup = this.data.goods.isSpellgroup == '1' ? this.data.goods.isSpellgroup : ''//拼团标识
    let order = {
      cartItems: [{
        cartId: this.data.goods.id,
        productId: this.data.goods.id,
        total: 1,
        skuId: this.data.goods.skuId,
        skuTitle: this.data.goods.skuTitle,
        marketprice: this.data.goods.marketprice,
      }]
    }
    wx.setStorageSync('order', JSON.stringify(order))

    wx.navigateTo({
      url: '/pages/index/place-order-entity/place-order-entity' +
      '?isSpellgroup=' + isSpellgroup + '&promoter=' + this.data.promoter + '&sgorderId=' + this.data.orderId
    })
  },
  //去首页逛逛
  toIndex(){
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  //我要开团
  toGoodItem(event){
    wx.navigateTo({
      url: '/subIndex/index/good-item/good-item?productId=' + event.currentTarget.dataset.productid
    })
  },

  //监听倒计时
  timeChange(e) {
    this.setData({
      timeData: e.detail
    });
  },
  //倒计时结束
  timeFinish(){
    this.setData({ serverTime: Date.parse(new Date()) })
    this.getGoodInfo();
  },

  invitationMonitor(){
    let _this = this;
    _this.setData({
      invitationShow: !_this.data.invitationShow
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (event) {
    this.setData({
      orderId: event.orderId,
      promoter: event.promoter,
      productId: event.productId,
      tShopId: event.tShopId || '',
      orderStatus: event.orderStatus || '',
    });
    this.getShopInfo();
  },
  getShopInfo(){
    let that = this;
    if(that.data.tShopId != app.getShop().id){
      app.requestUrl({
        method: 'GET',
        url: '/wxapi/shop/newNearest',
        data: {
          mid:that.data.tShopId,
          longitude: '112.98626',
          latitude: '28.25591',
          limit: 50,
          centreId: app.globalData.loginCentreId,
          flag: 2//1平台 2商户
        },
        load: 1
      }).then((res) => {
        wx.setStorageSync('shopInfo', JSON.stringify(res.data.data[0]));
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({ user: app.getUser(), serverTime: Date.parse(new Date()) })
    if(this.data.user.id == null){
      wx.navigateTo({ url: '/pages/login/login' })
      return;
    }

    //第一次注册，绑定门店
    if(this.data.user.upshopTid=='' || this.data.user.centreId=='')
      this.saveShopId();

    this.getGoodInfo();

    console.log(this.data.user)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var _this = this
    if (res.from === 'button') {//来自页面内转发按钮
      return {
        title: _this.data.user.nickname + '邀请你加入拼团',
        path: '/subIndex/index/good-spell/good-spell?orderId=' + _this.data.orderId + '&promoter='+ _this.data.promoter + '&tShopId='+ app.getShop().id + '&productId=' + _this.data.productId,
        imageUrl: _this.data.goods.thumb,
        success: function () {

        },
        fail: function () {
          wx.showToast({title: '分享失败', icon: 'none'})
        }
      }
    }
    else if (res.from === 'menu') {//右上角菜单转发按钮
      if(_this.data.orderStatus != -1){
        return {
          title:  _this.data.user.nickname + '邀请你加入拼团',
          path: '/subIndex/index/good-spell/good-spell?orderId=' + _this.data.orderId + '&promoter='+ _this.data.promoter + '&tShopId='+ app.getShop().id + '&productId=' + _this.data.productId,
          imageUrl: _this.data.goods.thumb,
          success: function () {

          },
          fail: function () {
            wx.showToast({title: '分享失败', icon: 'none'})
          }
        }
      }
    }
  }
})
